package com.sugon.thread;

import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;



/**
 * ForkJoin求最大值
 */
public class ForkJoinMax {

	public static void main(String[] args) {
		System.out.println("cpu核数"+Runtime.getRuntime().availableProcessors());
		Random r = new Random();
		int[] data = new int[40000000];
		for(int i = 0 ; i < data.length ; i++){
			data[i] = r.nextInt(100000000);
		}

		System.out.println(findMax1(data));
		System.out.println(findMax2(data));
		/*IntStream istream =IntStream.rangeClosed(1,40000000);
		int max= istream.parallel().max().getAsInt();
		System.out.println(max);*/
	}

	/**
	 * 普通方式
	 * @param data
	 * @return
	 */
	private static int findMax1(int[] data){
		long t1 = System.nanoTime();

		int max = data[0];
		for(int i = 1 ; i < data.length ; i++){
			if (data[i] > max) max = data[i];
		}

		long t2 = System.nanoTime();
		System.out.println(t2-t1);

		return max;
	}

	/**
	 * ForkJoin方式
	 * @param data
	 * @return
	 */
	private static int findMax2(int[] data){
		/**
		 * 用于有返回值的任务
		 */
		class MaxTask extends RecursiveTask<Integer>{
			int[] data;
			int start;
			int end;

			public MaxTask(int[] data, int start, int end) {
				super();
				this.data = data;
				this.start = start;
				this.end = end;
			}

			static final int THRESHOLD = 500000;
			@Override
			public Integer compute(){
				if (end - start <= THRESHOLD){
					int max = data[start];
					for(int i = start+1 ; i<end ; i++){
						if (data[i] > max) max=data[i];
					}
					return max;
				}
				else{
					int middle = (start+end)/2;
					MaxTask t1 = new MaxTask(data , start , middle);
					MaxTask t2 = new MaxTask(data , middle , end);

					invokeAll(t1,t2);

					//t1.fork();
					//t2.fork();

					int result1 = t1.join();
					int result2 = t2.join();
					if (result1 > result2 ) return result1;
					else return result2;
				}
			}
		}

		long t1 = System.nanoTime();
		ForkJoinPool pool = new ForkJoinPool();
		MaxTask main = new MaxTask(data , 0 , data.length);
		int result = pool.invoke(main);

		long t2 = System.nanoTime();
		System.out.println(t2-t1);
		return result;
	}
}
